﻿using Microsoft.SqlServer.Management.SqlParser.Common;
using Microsoft.SqlServer.Management.SqlParser.Parser;
using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;
using System;

namespace iTool.SQL.AIHandle
{
    public static class SqlUtils
    {
        public static ParseResult Parse(string sql)
        {
            var opts = new ParseOptions("GO", true, DatabaseCompatibilityLevel.Azure);
            opts.TransactSqlVersion = TransactSqlVersion.Azure;
            return Parser.Parse(sql);
        }

        public static void IterateSqlNode(SqlCodeObject sqlCodeObject, int indent = 0)
        {
            if (sqlCodeObject.Children == null
                || sqlCodeObject.GetType().FullName.Contains("OnePartObjectIdentifier")
                || sqlCodeObject.GetType().FullName.Contains("TwoPartObjectIdentifier")
                || sqlCodeObject is SqlIdentifier 
                )
                return;



            foreach (var child in sqlCodeObject.Children)
            {
                string text = $"{new string('-', indent)}Sql({indent}):{child.Sql}, Type:{child.GetType().Name}\n";
                //if (indent == 12)
                //{
                //    iPrint.Debug(text);
                //}
                //else if (indent == 9)
                //{
                //    iPrint.Error(text);
                //}
                //else
                //{
                //    Console.WriteLine(text);
                //}
                Console.WriteLine(text);
                IterateSqlNode(child, indent + 3);
            }
        }


    }
}
